package com.me.TextMissed_a1;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.provider.CallLog;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	public static final String UPDATE_PREFERENCE = "com.me.TextMissed_a1.UPDATE_PREFERENCE";
	private SampleReceiver myReceiver;
	
	private SharedPreferences preferences;
	private final static String MY_PREFS = "TextMissed_a1";
	private static final Pattern intervalPattern = Pattern.compile("(\\d+)([s|m|h]){1}");
	
	private static Long intervals;	
	//private Toast toast;		
	

    @Override
    public void onCreate() 
    {
    	myReceiver = new SampleReceiver();
    	IntentFilter filter = new IntentFilter(UPDATE_PREFERENCE);
    	registerReceiver(myReceiver, filter);
    	
    	//Pobierz SharedPreferences
        preferences = getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE);
        //intervals.setText(preferences.getString("intervals", "10m"));
        intervals = parseSingleInterval(preferences.getString("intervals", "10s"));
        
        //prepare Alarm Service to trigger Widget
        //Intent intent = new Intent(MyAppWidget.MY_WIDGET_UPDATE);
        Intent intent = new Intent(MyAppWidget.UPDATE_ONDEMAND);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService.this, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervals, pendingIntent);    	
		
    	Log.d("_TextMissed_a1_", "StartAtBootService Created Intervals: "+intervals);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	//Pobierz SharedPreferences
        preferences = getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE);
        //intervals.setText(preferences.getString("intervals", "10m"));
        intervals = parseSingleInterval(preferences.getString("intervals", "10s"));
        
    	Log.d("_TextMissed_a1_", "StartAtBootService -- onStartCommand() intervals: "+intervals);
    	
    	// We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    	Log.d("_TextMissed_a1_", "StartAtBootService Destroyed");
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        Log.d("_TextMissed_a1_", "onStart intervals: "+intervals);
        
        super.onStart(intent, startId);
        //timer.scheduleAtFixedRate(timerTask, 5*1000,  intervals);
    }
    
    //updateService Timer after change preferences
    public void updateService(String intervalsChange) {
    	intervals = parseSingleInterval(intervalsChange);
    	Log.d("_TextMissed_a1_", "Service updateService "+intervals);    	
    	//task.cancel();
        //timer.purge();        
        //task = new MyTimerTask();
        //timer.scheduleAtFixedRate(task, 0, intervals);       
        
        //Intent intent = new Intent(MyAppWidget.MY_WIDGET_UPDATE);
    	Intent intent = new Intent(MyAppWidget.UPDATE_ONDEMAND);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService.this, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervals, pendingIntent);
        
    }

    //Binder stuff here
    private final IBinder binder = new MyBinder();

    public IBinder onBind(Intent intent) { return binder; }

	public class MyBinder extends Binder {
		MyService getMyService() { 
			return MyService.this; 
		}
	} 
	
	private class SampleReceiver extends BroadcastReceiver {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	Log.d("_TextMissed_a1_", "MyService onReceive");
	    	
	    	if(intent.getAction().equals(UPDATE_PREFERENCE)) { //update preference
	    		//updateService();
			}
	    }
	}   

	
	private static long[] parseInterval(String str) {
		String[] intervals = str.split(",");
		int len = intervals.length;
		long[] a = new long[len];
		for (int i=0; i<len; i++) {
			long interval = parseSingleInterval(intervals[i]);
			if (interval == -1) {
				return null;
			}
			a[i] = interval;
		}
		return a;
	}

	private static long parseSingleInterval(String str) {
		Matcher m = intervalPattern.matcher(str);
		if (m.matches()) {
			int count = Integer.parseInt(m.group(1));
			String unit = m.group(2);
			long newInterval = 60000;
			if ("s".equals(unit)) {
				newInterval = count*1000;
			} else if ("m".equals(unit)) {
				newInterval = count*60*1000;
			} else if ("h".equals(unit)) {
				newInterval = count*60*60*1000;
			} else {
				return -1;					
			}
			return newInterval;				
		}
		return -1;
	}

}
